<?php 
namespace App\Console;

use Illuminate\Support\Facades\Storage;
use Illuminate\Console\Command;
use App\Bmob\BmobApi;
use Illuminate\Support\Facades\DB;

class MinApp extends Command
{
	protected $signature = 'minapp:save';

	public function handle()
	{

		// $data=$this->parse();
		// $api=new BmobApi('minapp');
		// $result=$api->batchCreate($data);
		// dd($result);
		// $tags=["15"];
		$tags=["15","12","22","7","20","6","18","10","11","8","13","21","9","17","14","19","23","5","16"];
		foreach ($tags as $key => $value) {
			# code...
			$this->loadfile($value);
		}
		
	}	

	private function loadfile($filename)
	{
		$files=Storage::disk('local')->files($filename); 
		foreach ($files as $key => $file) {
			# code...
			$items=$this->parse($file,$filename);
			// $api=new BmobApi('minapp');
			// $result=$api->batchCreate($items);
			DB::table('minapp')->insert($items);
		}
	}

	private function parse($file,$filename)
	{
        // dd($file);
        $jsonstr=Storage::disk('local')->get($file);
        $json=json_decode($jsonstr);
        $objects=$json->objects;
        $data=[];
        foreach ($objects as $key => $value) {
             
            $item=[
                'name'=>$this->toUTF8($value->name),
                'created_by'=>$value->created_by,
                'description'=>$this->toUTF8($value->description),
                'icon'=>$value->icon->image,
                'qrcode'=>$value->qrcode?$value->qrcode->image:'',
                'tag'=>$this->parseTag($value->tag),
                'screenshot'=>$this->parseScreenShot($value->screenshot),
                'tag_id'=>intval($filename),
                'created_at'=>date('Y-m-d H:m:s',time())
            ];
            $data[]=$item;
            // break;
            // dd($item);
        }
        return $data;
	}

	private function parseScreenShot($screenshot)
	{
		$images=array_pluck($screenshot,'id','image');
		return implode(array_keys($images),',');
	}

	private function parseTag($tag)
	{
		$tagname=array_pluck($tag,'id','name');
		return implode(array_keys($tagname),',');
	}

	private function toUTF8($value)
	{
		return mb_convert_encoding($value, 'UTF-8');
	}


	
} 

/**
	21 IT科技
	12 交通
	22 体育
	7  公益

	{"IT科技":"15","交通":"12","体育":"22","公益":"7","医疗":"20","商业服务":"6","商家自营":"18","富媒体":"10","工具":"11","快递邮政":"8","房地产":"13","政务民生":"21","教育":"9","旅游":"17","生活服务":"14","电商":"19","社交":"23","金融":"5","餐饮":"16"}

	let arr=[];$('.js-header-category').each(function(item){let obj={};obj[$(this).attr('ga-label')]=$(this).attr('data-category');arr.push(obj)});console.log(JSON.stringify(arr));
VM2176:1 [{"undefined":""},{"IT科技":"15"},{"交通":"12"},{"体育":"22"},{"公益":"7"},{"医疗":"20"},{"商业服务":"6"},{"商家自营":"18"},{"富媒体":"10"},{"工具":"11"},{"快递邮政":"8"},{"房地产":"13"},{"政务民生":"21"},{"教育":"9"},{"旅游":"17"},{"生活服务":"14"},{"电商":"19"},{"社交":"23"},{"金融":"5"},{"餐饮":"16"}]

["15","12","22","7","20","6","18","10","11","8","13","21","9","17","14","19","23","5","16"];


*/
